﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.Text;
using System.Globalization;
using IronOne.SalesOne.BusinessObjects;

namespace IronOne.SalesOne.SalesOneWeb
{
    public partial class SalesOneWeb : System.Web.UI.MasterPage
    {
        Facade.StructureFacade structureFacade = new Facade.StructureFacade();

        protected void Page_Prerender(object sender, EventArgs e)
        {

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            /*Dynamically generates Web.sitemap*/
            //GenerateXMLFile(Server.MapPath("~/Web.SiteMap"), modules);

            /*HtmlGenericControl si = new HtmlGenericControl();
            si.TagName = "script";
            si.Attributes.Add("type", "text/javascript");
            si.Attributes.Add("language", "JavaScript1.2");
            si.Attributes.Add("src", Page.ResolveUrl("~/JS/stmenu.js"));
            this.Page.Header.Controls.Add(si);*/

            if (!IsPostBack)
            {
                List<Module> modules = structureFacade.GetModules("ModuleId ASC");

                PopulateMenu(modules);//populate menu

                //PopulateTreeView(modules);//populate tree view - uncomment when needed
            }
            //CultureInfo culture = new CultureInfo("en-US");
            //culture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
            //System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
            //System.Threading.Thread.CurrentThread.CurrentCulture = culture;
        }

        private void PopulateSiteMap()
        {
            SiteMapPath map = new SiteMapPath();
            SiteMapNode parent = null;

            List<Module> modules = structureFacade.GetModules("ModuleId ASC");

            foreach (Module module in modules)
            {
                ////parentNode = new TreeNode(module.ModuleName, module.ModuleName);
                //parent = new SiteMapNode(module.ModuleName, module.ModuleName);

                //module.SubTasks = structureFacade.GetTasksForModule(module);
                //foreach (Task task in module.SubTasks)
                //{
                //    TreeNode childNode = new TreeNode(task.TaskName, task.Url);

                //    parentNode.ChildNodes.Add(childNode);
                //}
                //if (parentNode.ChildNodes.Count > 0)
                //{
                //    Tv.Nodes.Add(parentNode);

                //    parentNode.SelectAction = TreeNodeSelectAction.SelectExpand;
                //    parentNode.Collapse();
                //}
            }
        }

        /*
        protected void Tv_SelectedNodeChanged1(object sender, EventArgs e)
        {
            try
            {
                TreeView Tv1 = (TreeView)sender;
                int depth = Tv1.SelectedNode.Depth;
                string url = Tv1.SelectedNode.Value;
                string name = Tv1.SelectedNode.Text;
                Session["TreeView"] = Tv;

                if (depth == 0)
                {
                    foreach (TreeNode node in Tv.Nodes)
                    {
                        if ((bool)node.Expanded)
                        {
                            if (node.Text !=name)
                                node.Collapse();
                        }
                    }
                }
                else if (depth == 1)
                {
                    Response.Redirect("~" +url);
                    //Server.Transfer(Url);
                }
            }
            catch (Exception ex)
            {
                
            }
        }*/

        /*
        protected void Tv_Unload(object sender, EventArgs e)
        {
            new TreeViewState().SaveTreeView(Tv, this.GetType().ToString());
        }

        protected void Tv_NodeExpanded(object sender, EventArgs e)
        {
            //try
            //{
            //   TreeView Tv1 = (TreeView)sender;
            //    string s = Tv1.SelectedNode.Text;

            //    foreach (TreeNode node in Tv.Nodes)
            //    {
            //        if ((bool)node.Expanded)
            //        {
            //            if (node.Text != s)
            //                node.Collapse();
            //        }
            //    }
            //}
            //catch { }
        }*/

        private void GenerateXMLFile(string sFileName, List<Module> modules)
        {
            //Create XML
            Encoding enc = Encoding.UTF8;
            XmlTextWriter objXMLTW = new XmlTextWriter(sFileName, enc);
            try
            {
                objXMLTW.WriteStartDocument();//xml document open
                //'Top level (Parent element)
                //root node open
                objXMLTW.WriteStartElement("siteMap");
                //first Node of the Menu open
                objXMLTW.WriteStartElement("siteMapNode");
                //Title attribute set
                /*objXMLTW.WriteAttributeString("title", "Home");
                objXMLTW.WriteAttributeString("description",
                         "This is home");//Description attribute set
                objXMLTW.WriteAttributeString("url",
                         "http://www.home.com");//URL attribute set

                //Loop and create nodes*/


                foreach (Module module in modules)
                {
                    objXMLTW.WriteStartElement("siteMapNode");
                    objXMLTW.WriteAttributeString("title",
                                    module.ModuleName);
                    objXMLTW.WriteAttributeString("description",
                                          module.ModuleName);
                    objXMLTW.WriteAttributeString("url",
                                  module.ModuleName);

                    module.SubTasks = structureFacade.GetTasksForModule(module);
                    foreach (Task task in module.SubTasks)
                    {
                        if (!task.Url.Contains("index"))
                        {
                            objXMLTW.WriteStartElement("siteMapNode");
                            objXMLTW.WriteAttributeString("title",
                                            task.TaskName);
                            objXMLTW.WriteAttributeString("description",
                                                  task.TaskName);
                            objXMLTW.WriteAttributeString("url",
                                          task.Url);
                            objXMLTW.WriteEndElement();
                            //Close Child Element
                        }
                    }
                    objXMLTW.WriteEndElement();//Close the siteMapNode
                }

                objXMLTW.WriteEndElement();//Close the first siteMapNode
                objXMLTW.WriteEndDocument();//xml document closed
            }
            finally
            {
                objXMLTW.Flush();
                objXMLTW.Close();
            }
        }

        private void PopulateMenu(List<Module> modules)
        {
            //Menu menu = new Menu();
            foreach (Module module in modules)
            {
                MenuItem parentItem = new MenuItem(module.ModuleName);
                parentItem.ImageUrl = "~/images/menu_left3.jpg";
                parentItem.PopOutImageUrl = "~/images/menu_right.jpg";
                parentItem.SeparatorImageUrl = "~/images/menu_line.jpg";
                module.SubTasks = structureFacade.GetTasksForModule(module);

                foreach (Task task in module.SubTasks)
                {
                    List<TaskCredentials> taskCredentials = structureFacade.GetUserCredentials(HttpContext.Current.User.Identity.Name, task.Url);

                    if (HasPermission(taskCredentials))
                    {
                        MenuItem childrenItem = new MenuItem(task.TaskName, task.Url);
                        childrenItem.ImageUrl = "~/images/menu_left3.jpg";
                        childrenItem.SeparatorImageUrl = "~/images/menu_line.jpg";
                        parentItem.ChildItems.Add(childrenItem);
                    }
                }
                if (parentItem.ChildItems.Count > 0)
                {
                    SiteMenu.Items.Add(parentItem);
                }
            }

        }

        /*
        private void PopulateTreeView(List<Module> modules)
        {
            //TreeView Tv = (TreeView)this.FindControl("Tv");
            TreeNode parentNode = null;

            foreach (Module module in modules)
            {
                //parentNode = new TreeNode(module.ModuleName, module.ModuleName);
                parentNode = new TreeNode(module.ModuleName, module.ModuleName);

                module.SubTasks = structureFacade.GetTasksForModule(module);
                foreach (Task task in module.SubTasks)
                {
                    List<TaskCredentials> taskCredentials = structureFacade.GetUserCredentials(HttpContext.Current.User.Identity.Name, task.Url);

                    if (HasPermission(taskCredentials))
                    {
                        TreeNode childNode = new TreeNode(task.TaskName, task.Url);

                        parentNode.ChildNodes.Add(childNode);
                    }
                }
                if (parentNode.ChildNodes.Count > 0)
                {
                    Tv.Nodes.Add(parentNode);

                    parentNode.SelectAction = TreeNodeSelectAction.SelectExpand;
                    parentNode.Collapse();
                }
            }

            // set the default state of all nodes.

            Tv.CollapseAll();
            // get the saved state of all nodes.

            new TreeViewState().RestoreTreeView(Tv, this.GetType().ToString());
        }*/

        private bool HasPermission(List<TaskCredentials> list)
        {
            
                foreach (TaskCredentials rolePermission in list)
                {
                    if (rolePermission.Credentials != null)
                    {
                    foreach (string cred in rolePermission.Credentials.Split(','))
                    {
                        if (cred != "")
                            return true;

                    }
                }
            }
            return false;
        }

        protected void SiteMenu_MenuItemClick(object sender, MenuEventArgs e)
        {
            try
            {
                if (SiteMenu.SelectedItem.Value != SiteMenu.SelectedItem.Text)
                {
                    //Server.Transfer("~" + SiteMenu.SelectedItem.Value);
                    Response.Redirect("~" + SiteMenu.SelectedItem.Value);
                }
            }
            catch { }
        }


    }
}
